package com.java.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * @author jiangli
 * @date 2019/10/30 18:38
 * 处理消息的handler
 * TextWebSocketFrame,在netty中用来专门处理文本的对象,frame是消息的载体
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{
	//用于记录和管理所有客户端的channel
	private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
		//显示客户端的远程地址
		System.out.println(channelHandlerContext.channel().remoteAddress());
		//获取客户端传输来的消息
		String content = textWebSocketFrame.text();
		System.out.println("接收到的数据:"+content);

		channels.writeAndFlush(new TextWebSocketFrame("[服务器收到消息:]"+content+ " , "+LocalDateTime.now()));
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		channels.add(ctx.channel());
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		//当触发handlerRemoved,ChannelGroup会自动移除对应客户端的channel
		System.out.println("客户端断开,channel的长id:"+ctx.channel().id().asLongText());
		System.out.println("客户端断开,channel的短id:"+ctx.channel().id().asShortText());
	}
}
